<template>
  <div id="app" class="app">
    <animated-router v-if="!loading">
      <router-view></router-view>
    </animated-router>
    <loading-text v-else></loading-text>
  </div>
</template>
<script>
  import {http, eventEmitter, queryParse, isWeChat} from './common/js/util'
  import {STORAGE_TYPE, DEVICE_INFO} from './common/js/config'
  import LoadingText from './components/loading-text/loading-text'
  import AnimatedRouter from './components/animated-router/animated-router'
  import {share} from './common/js/share'

  function getUID(len, radix) {
    let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
    let uuid = []
    let i
    radix = radix || chars.length
    if (len) {
      for (i = 0; i < len; i++) {
        uuid[i] = chars[0 | Math.floor(Math.random() * radix)]
      }
    }
    return uuid.join('')
  }

  export default {
    components: {AnimatedRouter, LoadingText},
    data() {
      return {
        loading: true
      }
    },
    methods: {
      getDevice() {
        const temp = localStorage.getItem(STORAGE_TYPE.deviceToken)
        let deviceId = localStorage.getItem(STORAGE_TYPE.deviceId)
        if (!deviceId) {
          deviceId = getUID(8, 30)
          localStorage.setItem(STORAGE_TYPE.deviceId, deviceId)
        }
        if (temp) {
          this.loading = false
          return Promise.resolve()
        }
        return http({
          method: 'post',
          url: '/auth/getAccessToken',
          data: {
            appid: DEVICE_INFO.appid,
            appSecret: DEVICE_INFO.appSecret,
            device: deviceId
          }
        }).then(res => {
          if (res.accessToken) {
            localStorage.setItem(STORAGE_TYPE.deviceToken, res.accessToken)
          }
          return Promise.resolve()
        }).catch(() => {
          this.$message.alert('获取设备token失败')
          return Promise.resolve()
        })
      },
      // 获取微信公众号相关配置
      usJsSdk() {
        if (!isWeChat()) return Promise.resolve()
        return this.$post('/sapi/tpos/sign.xf', {url: window.location.href.split('#')[0]}).then(res => {
          share.weChatConfig = res.data
          return Promise.resolve()
        }).catch(() => {
          return Promise.resolve()
        })
      },
      // 获取微信code
      getWeChatCode() {
        return new Promise(async (resolve, reject) => {
          if (!isWeChat()) return resolve()
          const openid = localStorage.getItem('__OPEN_ID__')
          const code = queryParse().code
          // 如果openid存在，直接获取用户信息
          if (openid) {
            await this.getUserInfoByOpenId()
            resolve()
            // code存在时获取openid
          } else if (code) {
            await this.getOpenId()
            resolve()
            // 否则请求code
          } else {
            // 如果 __REFRESHED__ 已存在，说明已经进行过网页授权请求
            if (sessionStorage.getItem('__REFRESHED__')) return resolve()
            sessionStorage.setItem('__REFRESHED__', '1')
            window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${GLOBAL_CONF.appId}&redirect_uri=${encodeURIComponent(location.href)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
          }
        })
      },
      // 根据微信code获取微信openid
      getOpenId() {
        const code = queryParse().code
        return this.$post('sapi/tpos/getOpenId.xf', {code}).then(res => {
          if (res.data && res.data.openId) {
            localStorage.setItem('__OPEN_ID__', res.data.openId)
            return this.getUserInfoByOpenId()
          } else {
            return Promise.resolve()
          }
        }).catch(() => {
          return Promise.resolve()
        })
      },
      // 根据openid获取用户信息
      getUserInfoByOpenId() {
        const openId = localStorage.getItem('__OPEN_ID__')
        // 如果当前已有用户登录，则不再执行登陆操作
        if (localStorage.getItem('token')) return Promise.resolve()
        return this.$post('sapi/tpos/detection.xf', {openId}).then(res => {
          if (res.data.bound) {
            // 登陆成功
          }
          return Promise.resolve()
        }).catch(() => {
          return Promise.resolve()
        })
      }
    },
    watch: {},
    async created() {
      try {
        await this.getDevice()
      } catch (e) {}
      this.loading = false
      eventEmitter.on('refreshToken', () => [
        this.getDevice()
      ])
    }
  }
</script>
<style lang="scss">
  #app{
    height: 100%;
    width: 100%;
  }
</style>
